package cn.zhuama.org.service.impl;

import cn.zhuama.basic.service.impl.BaseServiceImpl;

import cn.zhuama.basic.util.Md5Utils;
import cn.zhuama.basic.util.StrUtils;
import cn.zhuama.org.domain.Employee;
import cn.zhuama.org.mapper.EmployeeMapper;
import cn.zhuama.org.service.IEmployeeService;
import cn.zhuama.system.mapper.EmployeeRoleMapper;
import cn.zhuama.user.domain.Logininfo;
import cn.zhuama.user.mapper.LogininfoMapper;
import com.sun.org.apache.xml.internal.security.Init;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeRoleMapper employeeRoleMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    @Transactional
    public void save(Employee employee) {
        InitEmployee(employee);

        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(Logininfo.ADMIN_USER);
        logininfo.setDisable(employee.getState()==1);
        logininfoMapper.insert(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.insert(employee);
        System.out.println(employee);
        employeeRoleMapper.insertEmpAndRole(employee);
    }
    @Override
    @Transactional
    public void editById(Employee employee) {  //
        /*employee编辑*/
        InitEmployee(employee);
        super.editById(employee);

        Logininfo logininfo = initLoginInfo(employee);
        logininfoMapper.updateById(logininfo);
        employeeRoleMapper.updateEmployeeAndRoleByEmpId(employee);
    }
    @Override
    @Transactional
    public void removeById(Long empId) {
        Long logininfo_id = employeeMapper.selectOne(empId).getLogininfo_id();
        //logininfoMapper.updateDisableById(logininfo_id);  //设置未禁用
        logininfoMapper.deleteById(logininfo_id);
        super.removeById(empId);
        employeeRoleMapper.deleteByEmpId(empId);
    }
    private void InitEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
    }

    private Logininfo initLoginInfo(Employee employee) {
        Logininfo logininfo = logininfoMapper.selectOne(employee.getLogininfo_id());
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(Logininfo.ADMIN_USER);
        logininfo.setDisable(employee.getState()==1);
        return logininfo;
    }

}
